﻿using System;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using NetProtocol.POD;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public class PlayerOrderComponent : TComponent
    {
        public UnitView unit;
        public bool Enable = true;
        public PlayerCommandQueue commands { get; } = new PlayerCommandQueue();

        private Vector2 skillMoveStart = Vector2.zero;
        private bool skillMoveing;

        public override void OnUpdate(float deltaTime)
        {
            if (!this.Enable)
            {
                return;
            }

            base.OnUpdate(deltaTime);
            var cmd = this.commands.Next();
            for (; cmd != null && BattleManager.Instance.ctrl.queueCtrl.InWaitCastSkill(out _, this.unit);)
            {
                cmd.Execute(this.unit);
                // 释放回对象池
                cmd.Free();

                cmd = this.commands.Next();
            }
        }

        public void CollectCommand(PlayerCommand rCommand)
        {
            if (rCommand != null)
            {
                this.ReceiveCommand(rCommand);
            }
        }

        private void ReceiveCommand(PlayerCommand rCommand)
        {
            this.commands.Add(rCommand);
        }

        public void SkillMove(int nSkillID, Vector2 rDir)
        {
            if (this.skillMoveStart == Vector2.zero)
            {
                this.skillMoveStart = rDir;

                BattleManager.Instance.ctrl.sceneCtrl.SetLight(false);
            }
            var rSkillViewComp = this.unit.GetComponent<SkillViewComponent>(ETComponentType.SkillViewComponent);
            var rCameraRotation = ManagerCenter.UI.MainCamera.transform.rotation;

            var rMoveDir = Vector3.zero;
            if (rDir != Vector2.zero)
            {
                rMoveDir = (rCameraRotation * Vector3.forward * rDir.y + rCameraRotation * Vector3.right * rDir.x);
                rMoveDir.y = 0;
                // 使用相机旋转后，有Y分量导致的转换后向量长度有畸变，归一化后再乘长度解决
                rMoveDir = rMoveDir.normalized * rDir.magnitude;
            }
            var rFromStart = rDir - this.skillMoveStart;
            this.skillMoveing = this.skillMoveing || rFromStart.sqrMagnitude >= 0.01f;
            rSkillViewComp?.ShowSelect(nSkillID, rMoveDir, this.skillMoveing);
        }

        public void Cancel(int nSkill)
        {
            this.skillMoveStart = Vector2.zero;
            this.skillMoveing = false;

            var rSkillViewComp = this.unit.GetComponent<SkillViewComponent>(ETComponentType.SkillViewComponent);
            rSkillViewComp.CancelSelect(nSkill);

            var rSceneCtrl = BattleManager.Instance.ctrl.sceneCtrl;
            rSceneCtrl.SetCameraState(BattleRenderSceneController.EBattleCameraState.Main);
            rSceneCtrl.SetLight(true);
        }

        public void Cast(int nSkill)
        {
            BattleManager.Instance.ctrl.sceneCtrl.SetLight(true);
            this.skillMoveStart = Vector2.zero;
            this.skillMoveing = false;

            // 尝试释放的技能与技能选择展示的技能不符
            var rSkillViewComp = this.unit.GetComponent<SkillViewComponent>(ETComponentType.SkillViewComponent);
            if (nSkill != rSkillViewComp.curSkill)
            {
                this.Cancel(rSkillViewComp.curSkill);
                LogGame.LogWarning("尝试释放的技能与技能展示中选择的技能不符，取消释放");
                return;
            }
            // 未选中目标 不释放
            if (nSkill > 0 && TableCenter.skill.Get(nSkill).IsLockTarget &&
                rSkillViewComp.selectUnit == null && BattleManager.Instance.ctrl.collisionCtrl.GetHitUnitNum(rSkillViewComp.collisionID) <= 0)
            {
                this.Cancel(rSkillViewComp.curSkill);
                return;
            }

            var rViewComp = this.unit.GetComponent<UnitViewComponent>(ETComponentType.UnitViewComponent);
            if (rViewComp == null)
            {
                return;
            }
            var rCurUnitPos = rViewComp.position;
            var rCurUnitForward = rViewComp.forward;
            // 默认使用指示器方向
            Transform rCurSelectTrans = null;
            if (rSkillViewComp.indicatorTrans)
            {
                rCurSelectTrans = rSkillViewComp.indicatorTrans;
            }
            else
            {
                //快速点击时，可能会有技能选择未加载出来的情况，则直接使用自身作为目标选择
                rCurSelectTrans = rViewComp.transform;
            }
            var rSelectLookAt = rCurSelectTrans.forward;
            var rSelectPos = rCurSelectTrans.position;
            // 在存在指定目标时，使用目标作为朝向
            var rTargetUnit = rSkillViewComp.selectUnit;
            if (rTargetUnit != null)
            {
                var rTargetViewComp = rTargetUnit.GetComponent<UnitViewComponent>(ETComponentType.UnitViewComponent);
                rSelectLookAt = rTargetViewComp.position - rCurUnitPos;
            }
            var rPOD = new BattleSkillPOD()
            {
                skillId = rSkillViewComp.curSkill,
                unitId = this.unit.GUID,
                pos = new Vector2POD(rCurUnitPos.x, rCurUnitPos.z),
                forward = new Vector2POD(rCurUnitForward.x, rCurUnitForward.z),
                targetId = rSkillViewComp.selectUnit?.GUID ?? 0,
                targetAspect = new Vector2POD(rSelectLookAt.x, rSelectLookAt.z),
                targetPos = new Vector2POD(rSelectPos.x, rSelectPos.z),
            };
            BattleManager.Instance.Cast(rPOD);
            rSkillViewComp.CancelSelect(nSkill);

            // BattleManager.Instance.ctrl.sceneCtrl.SetLight(true);
        }


        protected override void OnDispose()
        {
        }

        public override void OnCreate(TEntity entity)
        {
            this.unit = entity as UnitView;
        }
    }
}